﻿using System;
using ActionLogic.Impl;
using BlockLogic.Interface;
using BlockLogic.Interface.Blocks.Generator;
using ComputationalCore.Interface.RandomGenerator;
using BlockLogic.Impl.Enum;

namespace BlockLogic.Impl.Blocks.Generator
{
    public class Generator : Block, IGenerator
    {
        private IRequest _nextRequest;

        public int StartTime { get; set; }
        public IRequestBuffer OutputBuffer { get; set; }
        public IRequestBuffer CheckerBuffer { get; set; }
        public IRandomGenerator RandomGenerator { get; set; }

        public Generator(Guid id, BlockType type) : base(id, type)
        {
            StartTime = 0;
        }

        public override void Initialize()
        {
            _nextRequest = new Request(ID, StartTime);

            var executor = ActionExecutor.GetInstance();
            executor.Add(StartTime, Generate);
        }

        private void AddToAllBuffers(IRequest request)
        {
            if (request != null && StartTime < request.InitTime)
            {
                if (OutputBuffer != null)
                {
                    OutputBuffer.Add(request);
                }

                if (CheckerBuffer != null)
                {
                    CheckerBuffer.Add(request.Clone());
                }
            }
        }

        public void Generate()
        {
            AddToAllBuffers(_nextRequest);
            
            var nextInitTime = RandomGenerator.GetNext(_nextRequest.InitTime);
            _nextRequest = new Request(ID, nextInitTime);
            
            var executor = ActionExecutor.GetInstance();
            executor.Add(nextInitTime, Generate);
        }
    }
}
